package com.beifu.manager.controller;

import com.beifu.manager.dao.OrganizerMapper;
import com.beifu.manager.dao.UserInfoMapper;
import com.beifu.manager.model.Organizer;
import com.beifu.manager.model.UserInfo;
import com.beifu.manager.model.UserInfoExample;
import com.beifu.manager.service.user.UserService;
import com.beifu.manager.shiro.ActiveUser;
import com.mds.manager.utils.*;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value="/sysUser", produces="text/html;charset=UTF-8")
public class UserInfoController {

	private Logger Log = Logger.getLogger(this.getClass());
	
	@Autowired
	private UserService userService;

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private OrganizerMapper organizerMapper;
	
	@RequestMapping("/userIndex")
	public String goUserIndex(Model model){
		Log.info("进入用户管理界面");
		return "/system/user/user_index";
	}
	
	/**
	 * 用户列表分页数据
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUserPage")
	public String getPageData(Model model,HttpServletRequest request){
		Log.info(">>> 进入用户分页列表");
		String page = request.getParameter("pageNumber");
		String userName = request.getParameter("userName");
		String loginName = request.getParameter("loginName");
		
		UserInfoExample example = new UserInfoExample();
		UserInfoExample.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(userName)) {
			criteria.andUserNameLike("%"+userName+"%");
		}
		if (!StringUtils.isEmpty(loginName)) {
			criteria.andLoginNameLike("%"+loginName+"%");
		}
		
		PageUtils Page = new PageUtils(page);
		Page.setQueryParames(example);
		Page = userService.getUserPages(Page);
		return ResponseHelp.responseText(Page);
	}
	
	@RequestMapping("/goAddUserPage")
	public String goAddUserPage(Model model){
		Log.info("进入用户添加界面");
		List<Organizer> list = organizerMapper.selectByExample(null);
		model.addAttribute("organizationList", list);
		return "/system/user/user_add";
	}
	
	/**
	 * 用户名是否存在
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isExist")
	public String userNameIsExist(Model model,HttpServletRequest request) {
		String loginName = request.getParameter("loginName");
		
		UserInfoExample example = new UserInfoExample();
		UserInfoExample.Criteria criteria = example.createCriteria();
		criteria.andLoginNameEqualTo(loginName);
		List<UserInfo> list = userInfoMapper.selectByExample(example);
		if (ListUtils.isNotNull(list)) {
			return ResponseHelp.responseErrorText("用户名已存在！");
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 添加用户
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userAdd")
	public String userAdd(Model model,HttpServletRequest request){
		String userName = request.getParameter("userName");
		String loginName = request.getParameter("loginName");
		String organizerId = request.getParameter("organization");

		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
		userInfo.setLoginName(loginName);
		userInfo.setOrganizeId(Integer.valueOf(organizerId));
		userService.insert(userInfo);
		
		return ResponseHelp.responseText();
	}
	
	@RequestMapping("/goUpdateUserPage")
	public String goUpdateUserPage(Model model,HttpServletRequest request){
		Log.info("进入用户修改界面");
		
		String id = request.getParameter("id");
		UserInfo user = userInfoMapper.selectByPrimaryKey(Integer.decode(id));
		List<Organizer> list = organizerMapper.selectByExample(null);
		ActiveUser u = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
		model.addAttribute("organizationList", list);
		model.addAttribute("user", user);
		model.addAttribute("loginUserId", u.getUserId());
		return "/system/user/user_update";
	}
	
//	/**
//	 * 修改状态
//	 * @param model
//	 * @param request
//	 * @return
//	 */
//	@ResponseBody
//	@RequestMapping("/updateStatus")
//	public String updateStatus(Model model,HttpServletRequest request) {
//		String id = request.getParameter("id");
//		String status = request.getParameter("status");
//
//		if (id.equals("1")) {
//			return ResponseHelp.responseErrorText("admin用户不能被禁用");
//		}
//		User user = userService.selectByPrimaryKey(Long.decode(id));
//		user.setStatus(Integer.parseInt(status));
//		userService.updateByPrimaryKey(user);
//
//		return ResponseHelp.responseText();
//	}
	
	
	/**
	 * 更新用户
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userUpdate")
	public String userUpdate(Model model,HttpServletRequest request){
		String id = request.getParameter("id");
		String userName = request.getParameter("userName");
		String organizerId = request.getParameter("organization");
		String psd = request.getParameter("loginPassword");
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
		userInfo.setOrganizeId(Integer.valueOf(organizerId));
		
		UserInfo user = userInfoMapper.selectByPrimaryKey(Integer.decode(id));
		user.setUserName(userName);
		user.setOrganizeId(Integer.valueOf(organizerId));
		
		String password = new SimpleHash("MD5", psd, user.getLoginName()).toString();
		if (psd!=null && !"".equals(psd)) {
			user.setLoginPassword(password);
		}
		userService.updateByPrimaryKey(user);
		
		return ResponseHelp.responseText();
	}
	
	/**
	 * 删除用户
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userDel")
	public String userDel(Model model,HttpServletRequest request){
		BackMsg msg = new BackMsg();
		String ids = request.getParameter("ids");
		String[] idsArr = ids.split(",");
		for (String id : idsArr) {
			if ("1".equals(id)) {
				return ResponseHelp.responseErrorText("admin用户不允许被删除");
			}
		}
		userService.batchDelUser(idsArr);
		return ResponseHelp.responseText(msg);
	}
	
	/**
	 * 密码修改
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updatePass")
	public String updatePass(Model model,HttpServletRequest request){
		BackMsg msg = new BackMsg();
		String password = request.getParameter("password");
		String regPassword = request.getParameter("regPassword");
		String newPassword = request.getParameter("newPassword");

		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();

		String username = activeUser.getLoginName();
		
		if (!password.equals(regPassword)) {
			msg.setStatus(false);
			msg.setMessage("两次输入的密码不一致，请确认后再试");
			JSONObject json = new JSONObject(msg);
			return json.toString();
		}
		
		UserInfoExample userExample = new UserInfoExample();
		UserInfoExample.Criteria criteria = userExample.createCriteria();
		criteria.andLoginNameEqualTo(username);
		List<UserInfo> userList = userInfoMapper.selectByExample(userExample);
		if (ListUtils.isNotNull(userList)) {
			UserInfo user = userList.get(0);
			String passwordEncrypt = new SimpleHash("MD5", password, user.getLoginName()).toString();

			if (!user.getLoginPassword().equals(passwordEncrypt)) {
				msg.setStatus(false);
				msg.setMessage("旧密码不匹配，请重新确认");
				JSONObject json = new JSONObject(msg);
				return json.toString();
			}else{
				String newPasswordEncrypt = new SimpleHash("MD5", newPassword, user.getLoginName()).toString();
				user.setLoginPassword(newPasswordEncrypt);
				userService.updateByPrimaryKey(user);
			}
		}
		JSONObject json = new JSONObject(msg);
		return json.toString();
	}
}
